public class GetIntersectionNode {
    public static int length(MySingleList.ListNode head) {
        int length = 0;
        MySingleList.ListNode cur = head;
        while(cur != null) {
            length++;
            cur = cur.next;
        }

        return length;
    }

    public static void main1(String[] args) {
        MySingleList list = new MySingleList();
        list.addLast(1);
        int length = length(list.head);
        System.out.println(length);
    }
    public static MySingleList.ListNode getIntersectionNode(MySingleList.ListNode headA,MySingleList.ListNode headB) {
        MySingleList.ListNode curA = headA;
        MySingleList.ListNode curB = headB;

        //求两个链表的长度
        int lengthA = length(curA);
        int lengthB = length(curB);

        //求两个链表的长度之差
        int gap = lengthA - lengthB;
        int step = Math.abs(gap);
        int count = 0;
        //更长的链表先走
        if(gap > 0) {
            //A链表更长，所以A链表的头指针先走
            while(count < step) {
                count++;
                curA = curA.next;
            }

        }else {
            while(count < step) {
                count++;
                curB = curB.next;
            }
        }

        while(curA != null && curB != null) {
            if(curA == curB) {
                return curA;
            }

            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }

    public static void main(String[] args) {
        MySingleList list1 = new MySingleList();
        list1.addLast(5);
        list1.addLast(6);
        list1.addLast(1);
        list1.addLast(8);
        list1.addLast(4);
        list1.addLast(5);

        MySingleList list2 = new MySingleList();
        list2.addLast(4);
        list2.addLast(1);
        MySingleList.ListNode cur = list2.head;
        while(cur.next != null) {
            cur = cur.next;
        }

        MySingleList.ListNode last = cur;
        cur = list1.head;
        while(cur.val != 8) {
            cur = cur.next;
        }

        last.next = cur;

        list1.disPlay(list1.head);
        list2.disPlay(list2.head);

        MySingleList.ListNode resultNode = getIntersectionNode(list1.head,list2.head);
        if(resultNode == null) {
            System.out.println("无交点");
        }else{
            System.out.println(resultNode.val);
        }

    }
}

